#include "Level.h"
#include <stdexcept>

static Tile parseTileChar(char c) {
    if (c=='#') return Tile::Wall;
    if (c=='.') return Tile::Floor;
    if (c==' ') return Tile::Empty;
    return Tile::Floor;
}

Level Level::fromStringGrid(const std::vector<std::string>& lines) {
    if (lines.empty()) throw std::runtime_error("empty level");
    int h = (int)lines.size();
    int w = 0;
    for (auto& s : lines) if ((int)s.size()>w) w=(int)s.size();
    Level lvl;
    lvl.data.width = w;
    lvl.data.height = h;
    lvl.data.tiles.resize(w*h, Tile::Empty);
    for (int y=0;y<h;y++) {
        const std::string& row = lines[y];
        for (int x=0;x<w;x++) {
            char c = x<(int)row.size()?row[x]:' ';
            if (c=='$') lvl.data.boxes.push_back({x,y});
            else if (c=='@') lvl.data.player = {x,y};
            else if (c=='+') { lvl.data.player = {x,y}; lvl.data.goals.push_back({x,y}); }
            else if (c=='*') lvl.data.goals.push_back({x,y});
            Tile t = parseTileChar(c);
            lvl.data.tiles[y*w+x] = t;
        }
    }
    return lvl;
}

int Level::width() const { return data.width; }
int Level::height() const { return data.height; }
Tile Level::tileAt(int x, int y) const { return data.tiles[y*data.width+x]; }
const std::vector<Vec2i>& Level::goals() const { return data.goals; }
const std::vector<Vec2i>& Level::boxes() const { return data.boxes; }
const Vec2i& Level::playerStart() const { return data.player; }